package com.qianhui.dao;

import com.qianhui.common.CM;
import com.qianhui.common.IResult;
import com.qianhui.common.IStatus;
import com.qianhui.pojo.Order;
import com.qianhui.pojo.OrderReturn;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * A data access object (DAO) providing persistence and search support for
 * OrderReturn entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 *
 * @author MyEclipse Persistence Tools
 * @see com.qianhui.pojo.OrderReturn
 */
public class OrderReturnDAO extends BaseHibernateDAO
{
    private static final Logger log = LoggerFactory.getLogger(OrderReturnDAO.class);
    // property constants
    public static final String ORDER_ID = "orderId";
    public static final String ORDER_BUYER_EXPRESS_COMPANY = "orderBuyerExpressCompany";
    public static final String ORDER_BUYER_EXPRESS_NUMBER = "orderBuyerExpressNumber";
    public static final String ORDER_SELLER_EXPRESS_COMPANY = "orderSellerExpressCompany";
    public static final String ORDER_SELLER_EXPRESS_NUMBER = "orderSellerExpressNumber";
    public static final String ORDER_RETURN_TYPE = "orderReturnType";
    public static final String ORDER_RETURN_NOTES = "orderReturnNotes";
    public static final String ORDER_RETURN_SELLER_ID = "orderReturnSellerId";
    public static final String ORDER_RETURN_BEGIN_TIME = "orderReturnBeginTime";
    public static final String ORDER_RETURN_STATUS = "orderReturnStatus";

    public OrderReturn save(OrderReturn transientInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().saveOrUpdate(transientInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return transientInstance;
    }

    public List<OrderReturn> saveList(List<OrderReturn> list)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            for (OrderReturn temp : list)
            {
                getSession().saveOrUpdate(temp);
            }
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return list;
    }

    public int delete(OrderReturn persistentInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().delete(persistentInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.DELETE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.DELETE_SUCCESS;
    }

    public OrderReturn findById(java.lang.String id)
    {
        log.debug("getting OrderReturn instance with id: " + id);
        try
        {
            OrderReturn instance = (OrderReturn) getSession().get("com.qianhui.pojo.OrderReturn", id);
            return instance;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByProperty(String propertyName, Object value)
    {
        log.debug("finding OrderReturn instance with property: " + propertyName + ", value: " + value);
        try
        {
            String queryString = "from OrderReturn as model where model." + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByOrderId(Object orderId)
    {
        return findByProperty(ORDER_ID, orderId);
    }

    public List findByOrderBuyerExpressCompany(Object orderBuyerExpressCompany)
    {
        return findByProperty(ORDER_BUYER_EXPRESS_COMPANY, orderBuyerExpressCompany);
    }

    public List findByOrderBuyerExpressNumber(Object orderBuyerExpressNumber)
    {
        return findByProperty(ORDER_BUYER_EXPRESS_NUMBER, orderBuyerExpressNumber);
    }

    public List findByOrderSellerExpressCompany(Object orderSellerExpressCompany)
    {
        return findByProperty(ORDER_SELLER_EXPRESS_COMPANY, orderSellerExpressCompany);
    }

    public List findByOrderSellerExpressNumber(Object orderSellerExpressNumber)
    {
        return findByProperty(ORDER_SELLER_EXPRESS_NUMBER, orderSellerExpressNumber);
    }

    public List findByOrderReturnType(Object orderReturnType)
    {
        return findByProperty(ORDER_RETURN_TYPE, orderReturnType);
    }

    public List findByOrderReturnNotes(Object orderReturnNotes)
    {
        return findByProperty(ORDER_RETURN_NOTES, orderReturnNotes);
    }

    public List findByOrderReturnSellerId(Object orderReturnSellerId)
    {
        return findByProperty(ORDER_RETURN_SELLER_ID, orderReturnSellerId);
    }

    public List findByOrderReturnBeginTime(Object orderReturnBeginTime)
    {
        return findByProperty(ORDER_RETURN_BEGIN_TIME, orderReturnBeginTime);
    }

    public List findByOrderReturnStatus(Object orderReturnStatus)
    {
        return findByProperty(ORDER_RETURN_STATUS, orderReturnStatus);
    }

    public List findAll()
    {
        log.debug("finding all OrderReturn instances");
        try
        {
            String queryString = "from OrderReturn";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByIdList(List<String> idList)
    {
        try
        {
            String queryString = "from OrderReturn as model where model.orderReturnId in (:idList)";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameterList("idList", idList);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByIdsAndBuyerId(List<String> ids, String buyerId)
    {
        try
        {
            String sql = "from OrderReturn o where o.orderReturnId in (:ids) and o.buyerId=:buyerId order by o.orderReturnBeginTime asc";
            Query query = getSession().createQuery(sql);
            query.setParameterList("ids", ids);
            query.setParameter("buyerId", buyerId);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByBuyerIdAndIndexAndPageSize(String buyerId, int index, int pageSize)
    {
        try
        {
            String sql = "from OrderReturn o where o.buyerId=:buyerId order by o.orderReturnBeginTime desc";
            Query query = getSession().createQuery(sql);
            query.setParameter("buyerId", buyerId);
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountByBuyerId(String buyerId)
    {
        try
        {
            String sql = "select count(*) from OrderReturn o where o.buyerId=:buyerId";
            Query query = getSession().createQuery(sql);
            query.setParameter("buyerId", buyerId);
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public OrderReturn batch_save_return_and_order(OrderReturn orderReturn, Order order)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();

            getSession().saveOrUpdate(orderReturn);

            getSession().saveOrUpdate(order);

            tx.commit();
        } catch (Exception e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return orderReturn;
    }

    public List getListByIndexAndPageSizeAndStatusAnd_keyword(int index, int pageSize, String status, String keyword)
    {
        try
        {
            String sql = "from OrderReturn o where o.orderReturnStatus=:status :kSql order by o.orderReturnBeginTime :orderByStr";
            switch (status)
            {
                case IStatus.ORDER_RETURN_APPLY_VERIFYING:
                case IStatus.ORDER_RETURN_BUYER_RETURNING:
                case IStatus.ORDER_RETURN_SELLER_PROCESSING:
                    sql = sql.replaceAll(":orderByStr", IStatus.ORDER_BY_ASC);
                    break;
                case IStatus.ORDER_RETURN_HAVE_BEEN_COMPLETED:
                case IStatus.ORDER_RETURN_APPLY_REFUSED:
                    sql = sql.replaceAll(":orderByStr", IStatus.ORDER_BY_DESC);
                    break;
                default:
                    sql = sql.replaceAll(":orderByStr", IStatus.ORDER_BY_ASC);
                    break;
            }
            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "and (o.orderId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountByStatusAnd_keyword(String status, String keyword)
    {
        try
        {
            String sql = "select count(*) from OrderReturn o where o.orderReturnStatus=:status :kSql";
            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "and (o.orderId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAnd_keyword(int index, int pageSize, String keyword)
    {
        try
        {
            String sql = "from OrderReturn o :kSql order by o.orderReturnBeginTime desc";

            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "where (o.orderId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountBy_keyword(String keyword)
    {
        try
        {
            String sql = "select count(*) from OrderReturn o :kSql";
            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "where (o.orderId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public OrderReturn findByIdAndBuyerId(String id, String buyerId)
    {
        try
        {
            String sql = "from OrderReturn o where o.orderReturnId=:id and o.buyerId=:buyerId";
            Query query = getSession().createQuery(sql);
            query.setParameter("id", id);
            query.setParameter("buyerId", buyerId);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return (OrderReturn) tempList.get(0);
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List<OrderReturn> batch_save_return_and_order(List<OrderReturn> orderReturnList, List<Order> orderList)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();

            for (OrderReturn orTemp : orderReturnList)
            {
                getSession().saveOrUpdate(orTemp);
            }
            for (Order oTemp : orderList)
            {
                getSession().saveOrUpdate(oTemp);
            }

            tx.commit();
        } catch (Exception e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return orderReturnList;
    }

    public List getListByIndexAndPageSizeAndBeginTimeAndEndTime(int index, int pageSize, Date beginTime, Date endTime)
    {
        try
        {
            String sql = "from OrderReturn o where o.orderReturnBeginTime between :beginTime and :endTime order by o.orderReturnBeginTime asc";
            Query query = getSession().createQuery(sql);
            query.setParameter("beginTime", beginTime);
            query.setParameter("endTime", endTime);
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getTotalCountByBeginTimeAndEndTime(Date beginTime, Date endTime)
    {
        try
        {
            String sql = "select count(*) from OrderReturn o where o.orderReturnBeginTime between :beginTime and :endTime";
            Query query = getSession().createQuery(sql);
            query.setParameter("beginTime", beginTime);
            query.setParameter("endTime", endTime);
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

}